



//如果想在浏览器中实现 0ms 延时的定时器,window.postMessage()。

(
  function(){
    var timeouts = [];
    var messageName = 'zero-timeout-message';

    //保持setTimeout的形态，只接受单个函数的参数。
    function setZeroTimeout(fn){
      timeouts.push(fn);
      window.postMessage(messageName,"*")
    }

    function handleMessage(event){
      if(event.source == window && event.data == messageName){
        event.stopPropagation();
        if(timeouts.length > 0){
          var fn = timeouts.shift();
          fn();
        }
      }
    }
    window.addEventListener('message',handleMessage,true);
    window.setZeroTimeout = setZeroTimeout;
  }
)
